package com.kexilo.exception.handler;

import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.exception.ServiceException;
import com.kexilo.exception.deadletter.DeadLetterQueue;
import com.kexilo.exception.monitor.ExceptionMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.sql.SQLException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器 - exception插件版本
 * 集成异常监控、死信队列等功能
 *
 * @author Kexilo
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired(required = false)
    private ExceptionMonitor exceptionMonitor;

    @Autowired(required = false)
    private DeadLetterQueue deadLetterQueue;

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<Void> handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error("业务异常: {}", e.getMessage(), e);
        recordException(e, "Service", request);
        return R.error(e.getMessage());
    }

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public R<Void> handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        log.warn("权限校验异常: 用户访问了没有权限的资源 {}", request.getRequestURI());
        recordException(e, "Security", request);
        return R.error("没有权限，请联系管理员授权");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public R<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, 
                                                       HttpServletRequest request) {
        log.warn("请求方式不支持异常: {}", e.getMessage());
        recordException(e, "HTTP", request);
        return R.error("请求方式不支持，请检查请求方法");
    }

    /**
     * 请求路径不存在
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public R<Void> handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request) {
        log.warn("请求路径不存在: {}", request.getRequestURI());
        recordException(e, "HTTP", request);
        return R.error("请求路径不存在，请检查请求地址");
    }

    /**
     * 参数校验失败
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, 
                                                         HttpServletRequest request) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        
        log.warn("参数验证异常: {}", message);
        recordException(e, "Validation", request);
        return R.error("参数验证失败: " + message);
    }

    /**
     * 参数绑定失败
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleBindException(BindException e, HttpServletRequest request) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        
        log.warn("参数绑定异常: {}", message);
        recordException(e, "Validation", request);
        return R.error("参数绑定失败: " + message);
    }

    /**
     * 约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleConstraintViolationException(ConstraintViolationException e, 
                                                      HttpServletRequest request) {
        String message = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        
        log.warn("约束违反异常: {}", message);
        recordException(e, "Validation", request);
        return R.error("数据验证失败: " + message);
    }

    /**
     * 参数类型转换异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, 
                                                             HttpServletRequest request) {
        log.warn("参数类型转换异常: 参数 {} 无法转换为 {}", e.getName(), e.getRequiredType().getSimpleName());
        recordException(e, "Parameter", request);
        return R.error("参数类型错误，请检查参数格式");
    }

    /**
     * 数据库异常
     */
    @ExceptionHandler({SQLException.class, DataAccessException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<Void> handleDatabaseException(Exception e, HttpServletRequest request) {
        log.error("数据库异常: {}", e.getMessage(), e);
        recordException(e, "Database", request);
        
        // 发送到死信队列
        if (deadLetterQueue != null) {
            deadLetterQueue.sendToDeadLetter(request.getRequestURI(), e, "Database");
        }
        
        return R.error("数据库操作失败，请稍后重试");
    }

    /**
     * 空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<Void> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常: {}", e.getMessage(), e);
        recordException(e, "NullPointer", request);
        
        // 发送到死信队列
        if (deadLetterQueue != null) {
            deadLetterQueue.sendToDeadLetter(request.getRequestURI(), e, "NullPointer");
        }
        
        return R.error("系统内部错误，请联系管理员");
    }

    /**
     * 非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        log.warn("非法参数异常: {}", e.getMessage());
        recordException(e, "IllegalArgument", request);
        return R.error("参数错误: " + e.getMessage());
    }

    /**
     * 非法状态异常
     */
    @ExceptionHandler(IllegalStateException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<Void> handleIllegalStateException(IllegalStateException e, HttpServletRequest request) {
        log.warn("非法状态异常: {}", e.getMessage());
        recordException(e, "IllegalState", request);
        return R.error("操作状态错误: " + e.getMessage());
    }

    /**
     * 运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("运行时异常: {}", e.getMessage(), e);
        recordException(e, "Runtime", request);
        
        // 发送到死信队列
        if (deadLetterQueue != null) {
            deadLetterQueue.sendToDeadLetter(request.getRequestURI(), e, "Runtime");
        }
        
        return R.error("系统运行异常，请稍后重试");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常: {}", e.getMessage(), e);
        recordException(e, "System", request);
        
        // 发送到死信队列
        if (deadLetterQueue != null) {
            deadLetterQueue.sendToDeadLetter(request.getRequestURI(), e, "System");
        }
        
        return R.error("系统异常，请联系管理员");
    }

    /**
     * 记录异常
     */
    private void recordException(Exception e, String source, HttpServletRequest request) {
        try {
            String fullSource = source + ":" + request.getRequestURI();
            // 使用异常监控器记录异常
            if (exceptionMonitor != null) {
                exceptionMonitor.recordException(e, fullSource, request);
            } else {
                log.warn("ExceptionMonitor not available, exception not recorded: {} - {}", 
                    fullSource, e.getMessage());
            }
        } catch (Exception monitorException) {
            log.error("记录异常监控失败", monitorException);
        }
    }
}
